package com.ml.fdba.core.entity;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

@Component
@Scope("singleton")
public class TableList {

    private List<Table> tableList = new ArrayList<>();

    public class Table{

        private String name;

        private List<Field> fieldList = new ArrayList<Field>();

        public void setName(String name){
            this.name = name;
        }

        public String getName(){
            return this.name;
        }

        public void setFieldList(List<Map<String, Object>> fieldList){

            fieldList.forEach(item -> {
                Field field = new Field();
                field.setName(item.get("column_name").toString());
                field.setComment(item.get("column_comment").toString());
                field.setType(item.get("data_type").toString());
                this.fieldList.add(field);
            });
        }

        public List getFieldList(){
            return this.fieldList;
        }

        public class Field{

            private String name;
            private String comment;
            private String type;

            public void setName(String name){
                this.name = name;
            }

            public String getName(){
                return this.name;
            }

            public void setComment(String comment){
                this.comment = comment;
            }

            public String getCommente(){
                return this.comment;
            }
            public void setType(String type){
                this.type = type;
            }

            public String getType(){
                return this.type;
            }

        }
    }

    public void setTableList(List<Map<String, Object>> tableNameList){
        tableNameList.forEach(tableName -> {
            Table table = new Table();
            Iterator iterator = tableName.values().iterator();

            while (iterator.hasNext()){
                table.setName(iterator.next().toString());
            }

            this.tableList.add(table);
        });
    }

    public List<Table> getTableList(){
        return this.tableList;
    }

    public Table getTable(String tableName){
        List<Table> tableList= this.tableList.stream()
                .filter(item -> item.getName().equals(tableName))
                .collect(Collectors.toList());
        return tableList.get(0);
    }

    public List<Table.Field> getTableFields(String tableName){
        Table table = this.getTable(tableName);
        if(table != null){
            return table.getFieldList();
        }
        return  null;
    }
}
